package epam.bookShelf.database;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.h2.jdbcx.JdbcConnectionPool;

/**
 *  Data access object for BookShelf database.
 * @author Pustovit Michael, pustovitm@gmail.com
 */
public class BookShelfDAO_H2 implements BookShelfDAO {
    private final int MAX_CONN_COUNT;
    
    private JdbcConnectionPool pool;
    
    private final String URL, USER, PASS; 
    
    Logger log = null;
    
    private Properties dbProps = null;
    
    /**
     * Standard constructor for this DAO.
     * @param max_conn_count max connection count in connection pool 
     */
    public BookShelfDAO_H2() throws SQLException {
    	dbProps = new Properties();
        try {
            dbProps.load(
                    BookShelfDAO_H2.class.getResourceAsStream(
                            "/db.properties"));
        } catch (IOException e) {
            throw new SQLException(e);
        }
        
    	this.MAX_CONN_COUNT = Integer.valueOf(
    			dbProps.getProperty("max_conn_count"));
    	
        URL  = dbProps.getProperty("url") + dbProps.getProperty("path"); 
        USER = dbProps.getProperty("user"); 
        PASS = dbProps.getProperty("pass");
    }
    
    /**
     * DAO constructor for tests.
     * @param max_conn_count max connection count in connection pool 
     */
    public BookShelfDAO_H2(String path) throws SQLException {       
    	this.MAX_CONN_COUNT = 2;
    	
        URL  = path; 
        USER = "su"; 
        PASS = "";
    }    
    
    @Override
    public void start() throws SQLException {
        pool = createPool();
        pool.setMaxConnections(MAX_CONN_COUNT);
    }
    
    @Override
    public void stop() throws SQLException {
        pool.dispose();
    }
    
    @Override
    public Connection getConnection() throws SQLException {
        return pool.getConnection();
    }
    
    private JdbcConnectionPool createPool() throws SQLException {
    	try {
    		Class.forName("org.h2.Driver");    		
    	} catch (ClassNotFoundException e) {
            throw new SQLException(e);
        }

        return JdbcConnectionPool.create(URL, USER, PASS);        
    }
    
    @Override
    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("Connection close error");
            }
        }
    }

    @Override
    public void closeStatement(PreparedStatement myStat) {
        if (myStat != null) {
            try {
                myStat.close();
            } catch (SQLException e) {
                ;
            }
        }
    }            
}

